import json
from typing import Any
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
site_packages_dir = os.path.join(current_dir, '.venv', 'Lib', 'site-packages')
sys.path.append(site_packages_dir)
sys.stdout.reconfigure(encoding='utf-8')  # 新增编码强制设定
from mcp.server.fastmcp import FastMCP
import requests
import asyncio

mcp = FastMCP("WeatherServer")

@mcp.tool()
async def get_weather(city="Beijing") -> str:
    """
    输入指定城市的英文名称，返回该城市的今日天气信息。
    :param city: 城市英文名称
    :return: 格式化后的天气信息
    """
    weather_response = await query_weather(city)
    return weather_response

API_KEY = "4a19acd5e99591998e41d39e75698a38" # 去https://openweathermap.org/申请个key， 然后记得在邮箱里激活一下

async def query_weather(city="Beijing", units="metric", language="zh_cn"):
    # 构建请求URL
    url = "https://api.openweathermap.org/data/2.5/weather"
    # 设置查询参数
    params = {
        "q": city,                 # 查询的城市，默认为北京
        "appid": API_KEY,          # API密钥
        "units": units,            # 测量单位，默认为摄氏度
        "lang": language           # 输出语言，默认为简体中文
    }
    # 发送GET请求
    response = requests.get(url, params=params)
    # 检查响应状态
    if response.status_code == 200:
        # 解析响应数据
        data = response.json()
        # 提取数据
        city = data.get("name", "未知")
        country = data.get("sys", {}).get("country", "未知")
        temperature = data.get("main", {}).get("temp", "N/A")
        description = data.get("weather", [{}])[0].get("description", "未知")
        humidity = data.get("main", {}).get("humidity", "N/A")
        wind_speed = data.get("wind", {}).get("speed", "N/A")

        return (
            f"{city}, {country}\n"
            f"天气: {description}\n"
            f"温度: {temperature}°C\n"
            f"湿度: {humidity}%\n"
            f"风速: {wind_speed} m/s\n"
        )
    
    else:
        print(f"查询失败，状态码：{response.status_code}")
        print("响应数据：", response.text)

if __name__ == "__main__":
    mcp.run(transport='stdio')